import { useRef, useCallback, useEffect } from 'react';

/**
 * 自定义Hook：管理blob URL的生命周期
 * 自动跟踪和清理blob URLs，防止内存泄漏
 */
export function useBlobUrlManager() {
  const blobUrlsRef = useRef(new Set());
  
  // 添加blob URL到跟踪集合
  const trackBlobUrl = useCallback((url) => {
    if (typeof url === 'string' && url.startsWith('blob:')) {
      blobUrlsRef.current.add(url);
    }
  }, []);
  
  // 清理单个blob URL
  const cleanupBlobUrl = useCallback((url) => {
    if (typeof url === 'string' && url.startsWith('blob:')) {
      URL.revokeObjectURL(url);
      blobUrlsRef.current.delete(url);
    }
  }, []);
  
  // 创建blob URL并自动跟踪
  const createBlobUrl = useCallback((file) => {
    const url = URL.createObjectURL(file);
    trackBlobUrl(url);
    return url;
  }, [trackBlobUrl]);
  
  // 批量清理不再使用的blob URLs
  const cleanupUnusedUrls = useCallback((currentUrls) => {
    const currentUrlSet = new Set(currentUrls);
    
    blobUrlsRef.current.forEach(url => {
      if (!currentUrlSet.has(url)) {
        URL.revokeObjectURL(url);
        blobUrlsRef.current.delete(url);
      }
    });
    
    // 更新跟踪集合
    blobUrlsRef.current = currentUrlSet;
  }, []);
  
  // 清理所有blob URLs
  const cleanupAllUrls = useCallback(() => {
    blobUrlsRef.current.forEach(url => {
      URL.revokeObjectURL(url);
    });
    blobUrlsRef.current.clear();
  }, []);
  
  // 组件卸载时自动清理
  useEffect(() => {
    return () => {
      cleanupAllUrls();
    };
  }, [cleanupAllUrls]);
  
  return {
    trackBlobUrl,
    cleanupBlobUrl,
    createBlobUrl,
    cleanupUnusedUrls,
    cleanupAllUrls
  };
}